<?php
/**
 * Created by PhpStorm.
 * User: 64423
 * Date: 2018/10/10
 * Time: 11:26
 */

namespace app\shop\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\shop\model\BrandModel;
use app\shop\model\GoodsCategoryModel;
use app\shop\model\GoodsModel;
use app\shop\model\GoodsSpecModel;
use app\shop\model\GoodsTypeModel;
use app\shop\model\GoodsAttrModel;
use app\shop\model\GoodsAttributeModel;
use app\shop\model\SpecItemModel;
use app\shop\model\SpecModel;
use app\shop\model\SpecPriceModel;

class Goods extends Admin
{
    public function index()
    {
        $list = db('goods')->order('id')->paginate(10);
        $page = $list->render();
        $rows = [
            ['id', 'ID'],
            ['goods_name','商品名称'],
            ['category_id','分类名称'],
            ['sort_order','排序','text.edit'],
            ['is_hot','热卖','switch'],
            ['is_new','新品','switch'],
            ['right_button','操作']
        ];
        return ZBuilder::make('table')
            ->setPageTitle('商品列表')
            ->setTableName('goods')
            ->hideCheckbox()
            ->addColumns($rows)
            ->addTopButton('add')
            ->addRightButtons('edit,delete')
            ->setPages($page)
            ->setRowList($list)
            ->fetch();
    }

    public function add()
    {
        if(request()->isPost()){
            $this->store();
        }
        $brand_list = db('brand')->order('sort_order desc')->column('name','id');
        $category_list = db('category')->order('sort_order desc')->column('name','id');
        $type_list = db('goods_type')->select();
        //分类树状
        $this->assign('brand_list',$brand_list);
        $this->assign('category_list',$category_list);
        $this->assign('type_list',$type_list);
        return $this->fetch();


    }

    public function edit( $id=0 )
    {
        if(request()->isPost()){
            $this->store();
        }
        $brand_list = db('brand')->order('sort_order desc')->column('name','id');
        $category_list = db('category')->order('sort_order desc')->column('name','id');
        $type_list = db('goods_type')->select();
        $goods_info = db('goods')->where('id',$id)->find();

        $goods_info['photos_url_list'] = explode(",",$goods_info['photos_url']);

        $this->assign('brand_list',$brand_list);
        $this->assign('category_list',$category_list);
        $this->assign('type_list',$type_list);
        $this->assign('goods_info',$goods_info);
        return $this->fetch();

    }

    /**
     * 动态获取商品规格选择框 根据不同的数据返回不同的选择框
     */
    public function ajaxGetSpecSelect(){
        $goods_id =  input('get.goods_id');
        $type_id =  input('get.type_id');
        $spec_list = db('spec')->where("type_id",$type_id)->order('sort_order desc')->select();
        foreach($spec_list as $k => $v){
            $spec_list[$k]['spec_item'] = db('spec_item')->where("spec_id",$v['id'])->order('id')->column('item','id'); // 获取规格项

        }

        $items_id = db('spec_price')->where('goods_id',$goods_id)->column( "key");
        $items_ids = [];
        foreach ($items_id as $k=>$v){
            $_item = explode('_', $v);
            $items_ids = array_merge($items_ids,$_item);
        }


        $this->assign('items_ids',$items_ids);

        $this->assign('spec_list',$spec_list);
        return $this->fetch('ajax_spec_select');
    }

    /**
     * 动态获取商品规格输入框 根据不同的数据返回不同的输入框
     */
    public function ajaxGetSpecInput(){

        $goods_id = input('get.goods_id',0);
        $spec_arr = input('post.spec_arr/a',[[]]);
        if(isset($spec_arr[0]) && empty($spec_arr[0])){
            return;
        }
        if(empty($spec_arr)){
            return;
        }
        foreach ($spec_arr as $k => $v)
        {
            $spec_arr_sort[$k] = count($v);
        }

        asort($spec_arr_sort); //按照键值对关联数组进行升序排序
        foreach ($spec_arr_sort as $key =>$val)
        {
            $spec_arr2[$key] = $spec_arr[$key];
        }

        $clo_name = array_keys($spec_arr2);     //返回包含数组中所有键名的一个新数组

        $spec_arr2 = combineDika($spec_arr2); //  获取 规格的 笛卡尔积

        $spec = db('spec')->column('name','id'); // 规格表
        $specItem = db('spec_item')->column('item,spec_id','id');//规格项

        $keySpecGoodsPrice = db('spec_price')->where('goods_id',$goods_id)->column('key,key_name,price,store_num,sku','key');//规格项

        $str = "<table class='table table-bordered' id='spec_input_tab' >";
        $str .="<tr>";
        // 显示第一行的数据
        foreach ($clo_name as $k => $v)
        {
            $str .=" <td><b>{$spec[$v]}</b></td>";
        }
        $str .="<td><b>价格</b></td>
               <td><b>库存</b></td>
               <td><b>SKU</b></td>
             </tr>";
        // 显示第二行开始

        foreach ($spec_arr2 as $k => $v)
        {
            $str .="<tr>";
            $item_key_name = array();
            foreach($v as $k2 => $v2)
            {
                $str .="<td class='link'>{$specItem[$v2]['item']}</td>";
                $item_key_name[$v2] = $spec[$specItem[$v2]['spec_id']].':'.$specItem[$v2]['item'];
            }
            ksort($item_key_name);
            $item_key = implode('_', array_keys($item_key_name));
            $item_name = implode(' ', $item_key_name);

            isset($keySpecGoodsPrice[$item_key]['price']) ? false : $keySpecGoodsPrice[$item_key]['price'] = 0; // 价格默认为0
            isset($keySpecGoodsPrice[$item_key]['store_num']) ? false : $keySpecGoodsPrice[$item_key]['store_num'] = 0; //库存默认为0
            isset($keySpecGoodsPrice[$item_key]['sku']) ? false : $keySpecGoodsPrice[$item_key]['sku'] = ''; //库存默认为0

            $str .="<td><input class='form-control' name='item[$item_key][price]' value='{$keySpecGoodsPrice[$item_key]['price']}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")' /></td>";
            $str .="<td><input class='form-control' name='item[$item_key][store_num]' value='{$keySpecGoodsPrice[$item_key]['store_num']}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")'/></td>";
            $str .="<td><input class='form-control' name='item[$item_key][sku]' value='{$keySpecGoodsPrice[$item_key]['sku']}' />
                <input type='hidden' name='item[$item_key][key_name]' value='$item_name' /></td>";
            $str .="</tr>";
        }
        $str .= "</table>";
        return $str;
    }



    public function ajaxGetAttr(){
        $goods_id =  input('get.goods_id');
        $type_id =  input('get.type_id');

        $attr_list = db('attr')->where('type_id',$type_id)->select();;

        $html = '';
        foreach($attr_list as $k => $v){
            $goods_attr = db('goods_attr')->where('attr_id',$v['attr_id'])->where('goods_id',$goods_id)->select();
            if(count($goods_attr) == 0)
                $goods_attr[] = array('goods_attr_id' =>'','goods_id' => '','attr_id' => '','attr_value' => '','attr_price' => '');
            foreach ($goods_attr as $k2=> $v2){
                if($v['attr_input_type']==0){

                    $html .= "<tr class='attr_".$v['attr_id']."'><td class='link'> ".$v['attr_name']."</td>";
                    $html .= "<td><input class='form-control' type='text' size='40' value='".($goods_id ? $v2['attr_value'] : $v['attr_values'])."' name='attr_".$v['attr_id']."[]'></td></tr>";

                }else if($v['attr_input_type']==1){
                    $item = explode(",",$v['attr_values']);
                    $html .= "<tr class='attr_252'><td class='link'>".$v['attr_name']."</td>";
                    $html .= "<td><select name='attr_".$v['attr_id']."[]' style='width: 100%' class='se'>";
                    foreach ($item as $k3=>$v3){
                        // 编辑的时候 有选中值
                        $v3 = preg_replace("/\s/","",$v3);
                        if($v2['attr_value'] == $v3)
                            $html .= "<option selected='selected' value='{$v3}'>{$v3}</option>";
                        else
                            $html .= "<option value='{$v3}'>{$v3}</option>";

                    }
                    $html .= "</select></td>";

                }
            }

        }
        return  $html;


    }



    public function delete($ids=0)
    {
        if($ids == 0){
            $this->error('参数错误');
        }
        db('goods')->where('id',$ids)->delete();
        db('goods_attr')->where('goods_id',$ids)->delete();
        db('spec_price')->where('goods_id',$ids)->delete();
        $this->success('删除成功');
    }

    private function store()
    {
        $data = input('post.');

        $id = input('param.id',0);

        $data['is_sell'] = intval(isset($data['is_sell']));
        $data['is_hot'] = intval(isset($data['is_hot']));
        $data['is_rec'] = intval(isset($data['is_rec']));
        $data['is_new'] = intval(isset($data['is_new']));
        $data['virtual'] = intval(isset($data['virtual']));

        // 保存商品基本信息
        if($id == 0){
            $goods_id = db('goods')->insertGetId($data);
        }else{
            db('goods')->where('id',$id)->update($data);
            $goods_id = $id;
        }

        $this->saveGoodsSpec($data, $goods_id);
        //保存商品属性
        $this->saveGoodsAttr($data,$goods_id);

        $this->success('保存成功',url('index'));

    }

    // 保存规格
    private function saveGoodsSpec($data, $goods_id)
    {
        if(!isset($data['type_id']))
        {
            return;
        }
        db('spec_price')->where('goods_id',$goods_id)->delete();
        if(isset($data['item']) && $data['item'])
        {

            foreach($data['item'] as $k => $v)
            {
                // 批量添加数据
                $v['price'] = trim($v['price']);
                $v['store_num'] = trim($v['store_num']); // 记录商品总库存
                $v['sku'] = trim($v['sku']);
                $dataList[] = ['goods_id'=>$goods_id,'key'=>$k,'key_name'=>$v['key_name'],'price'=>$v['price'],'store_num'=>$v['store_num'],'sku'=>$v['sku']];

            }

            db("spec_price")->insertAll($dataList);

        }
    }

    // 保存属性
    private function saveGoodsAttr($data,$goods_id)
    {
        // 属性类型被更改了 就先删除以前的属性类型 或者没有属性 则删除
        if(!isset($data['type_id']))
        {
            db('goods_attr')->where('goods_id',$goods_id)->delete();
            return;
        }

        $GoodsAttrList = db('goods_attr')->where('goods_id',$goods_id)->select();
        $old_goods_attr = array(); // 数据库中的的属性  以 attr_id _ 和值的 组合为键名
        foreach($GoodsAttrList as $k => $v)
        {
            $old_goods_attr[$v['attr_id'].'_'.$v['attr_value']] = $v;
        }
        // post 提交的属性  以 attr_id _ 和值的 组合为键名
        foreach($data as $k => $v)
        {
            $attr_id = str_replace('attr_','',$k);
            if(!strstr($k, 'attr_') || strstr($k, 'attr_price_')){
                continue;
            }
            foreach ($v as $k2 => $v2)
            {
                $v2 = str_replace('_', '', $v2); // 替换特殊字符
                $v2 = str_replace('@', '', $v2); // 替换特殊字符
                $v2 = trim($v2);
                if(empty($v2))
                    continue;

                $tmp_key = $attr_id."_".$v2;
//                $post_attr_price = input("post.attr_price_{$attr_id}");
//                $attr_price = $post_attr_price[$k2];
//                $attr_price = $attr_price ? $attr_price : 0;
                if(array_key_exists($tmp_key , $old_goods_attr)) // 如果这个属性 原来就存在
                {
//                    if($old_goods_attr[$tmp_key]['attr_price'] != $attr_price) // 并且价格不一样 就做更新处理
//                    {
//                        $goods_attr_id = $old_goods_attr[$tmp_key]['goods_attr_id'];
////                        db('goods_attr')->where('goods_attr_id',$goods_attr_id)->update(['attr_price'=>$attr_price]);
//
//                    }
                }
                else // 否则这个属性 数据库中不存在 说明要做删除操作
                {
                    $d = array('goods_id'=>$goods_id,'attr_id'=>$attr_id,'attr_value'=>$v2);

                    db('goods_attr')->insert($d);

                }
                unset($old_goods_attr[$tmp_key]);
            }

        }

        // 没有被 unset($old_goods_attr[$tmp_key]); 掉是 说明 数据库中存在 表单中没有提交过来则要删除操作
        foreach($old_goods_attr as $k => $v)
        {
            db('goods_attr')->where('goods_attr_id',$v['goods_attr_id'])->delete();

        }

    }



}